#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow * MainWindow::ptrstuSql = nullptr;
int idx = 0, total = 0;
bool state = false;
QString str;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //this->move(0,0);
    int width = 1500;
    int height = 900;
    this->setFixedSize(width,height);

    db=QSqlDatabase::addDatabase("QSQLITE");
    auto str = QCoreApplication::applicationDirPath() + "/test2.db";
    qDebug() << str;
    db.setDatabaseName("test2.db");
//    db.setDatabaseName("str");
    db.open();
    QSqlQuery sql;
    //sql.exec("create table userinfo(uid,username)");
    //sql.exec("insert into userinfo values(3,'111')");
//    User user;
//    user.id = 6;
//    user.name = "李四";
//    addUser(user);

    //ui->listWidget->resize(365,400);
    //设置QListWidget的显示模式
    ui->listWidget->setViewMode(QListView::IconMode);
    //设置QListWidget中单元项的图片大小
    ui->listWidget->setIconSize(QSize(120,120));
    //设置QListWidget中单元项的间距
    ui->listWidget->setSpacing(22);
    //设置自动适应布局调整（Adjust适应，Fixed不适应），默认不适应
    ui->listWidget->setResizeMode(QListWidget::Adjust);
    //设置不能移动
    ui->listWidget->setMovement(QListWidget::Static);

    connect(ui->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(listWidgetClicked(QListWidgetItem*)));

//    getPageUser(2, 3);
//    delUser(3);

    updateMainWindow();

}

QList<User> MainWindow::getPageUser(int page, int cnt)
{
    QList<User> list;
    QSqlQuery sql;
    QString strsql = QString("select * from patient_base_info limit %1 offset %2").arg(cnt).arg((page - 1) * cnt);
    sql.exec(strsql);
    User user;
    while(sql.next())
    {
        user.id = sql.value(0).toUInt();
        user.name = sql.value(1).toString();
        list.push_back(user);
    }
    return list;
}

int MainWindow::getUserCnt()
{
    QSqlQuery sql;
    int res = 0;
    sql.exec("select count(*) from patient_base_info");
    while(sql.next())
    {
        res = sql.value(0).toUInt();
    }
    return res;
}

int MainWindow::getUserCntByName(QString name)
{
    QSqlQuery sql;
    int res = 0;
    sql.exec("select count(*) from patient_base_info where name like '%" + name + "%'");
    while(sql.next())
    {
        res = sql.value(0).toUInt();
    }
    return res;
}

User MainWindow::getUserById(int id)
{
    User user;
    QSqlQuery sql;
    QString strsql = QString("select * from patient_base_info where id=%1").arg(id);
    qDebug() << strsql;
    sql.exec(strsql);
    while(sql.next())
    {
        user.id = sql.value(0).toUInt();
        user.name = sql.value(1).toString();
        user.sex = sql.value(2).toString();
        user.idcard = sql.value(3).toString();
        user.address = sql.value(4).toString();
        user.phone = sql.value(5).toString();
    }
    return user;
}

bool MainWindow::addUser(User user)
{
    QSqlQuery sql;
    QString strsql = QString("insert into patient_base_info(name, sex, idcard, address, phone) values ('%1', '%2', '%3', '%4', '%5');")
            .arg(user.name)
            .arg(user.sex)
            .arg(user.idcard)
            .arg(user.address)
            .arg(user.phone);
    qDebug() << strsql;
    return sql.exec(strsql);
}

bool MainWindow::delUser(int id)
{
    QSqlQuery sql;
    QString strsql = QString("delete from patient_base_info where id=%1").arg(id);
    return sql.exec(strsql);
}

bool MainWindow::updateUser(User user)
{
    QSqlQuery sql;
    QString strsql = QString("update patient_base_info set name='%1',sex='%2',idcard='%3',address='%4',phone='%5' where id=%6")
            .arg(user.name)
            .arg(user.sex)
            .arg(user.idcard)
            .arg(user.address)
            .arg(user.phone)
            .arg(user.id);
    qDebug() << strsql;
    return sql.exec(strsql);
}

QList<Info> MainWindow::getAllInfoById(int id)
{
    QList<Info> list;
    QSqlQuery sql;
    QString strsql = QString("select * from patient_detail_info where pid=%1").arg(id);
    sql.exec(strsql);
    while(sql.next())
    {
        Info info;
        info.id = sql.value(0).toInt();
        info.pid = sql.value(1).toInt();
        info.visit_time = sql.value(2).toString();
        info.first_symptom = sql.value(3).toString();
        info.height = sql.value(4).toString();
        info.weight = sql.value(5).toString();
        info.comorbidity = sql.value(6).toString();
        info.thymic_disease = sql.value(7).toString();
        info.myasthenia = sql.value(8).toString();
        info.antibody_test = sql.value(9).toString();
        info.blood_test = sql.value(10).toString();
        info.technical_inspection = sql.value(11).toString();
        info.scale_evaluation1 = sql.value(12).toString();
        info.scale_evaluation2 = sql.value(13).toString();
        info.diagnosis1 = sql.value(14).toString();
        info.diagnosis2 = sql.value(15).toString();
        info.treatment_plan = sql.value(16).toString();
        info.MGFA = sql.value(17).toString();
        list.push_back(info);
    }
    return list;
}

Info MainWindow::getFirstInfoById(int id)
{
    QSqlQuery sql;
    QString strsql = QString("select * from patient_detail_first_info where pid=%1").arg(id);
    sql.exec(strsql);
    Info info;
    while(sql.next())
    {
        info.id = sql.value(0).toInt();
        info.pid = sql.value(1).toInt();
        info.visit_time = sql.value(2).toString();
        info.first_symptom = sql.value(3).toString();
        info.age = sql.value(4).toInt();
        info.elapsed_time = sql.value(5).toString();
        info.height = sql.value(6).toString();
        info.weight = sql.value(7).toString();
        info.smoking_history = sql.value(8).toString();
        info.previous_illnesses = sql.value(9).toString();
        info.comorbidity = sql.value(10).toString();
        info.thymic_disease = sql.value(11).toString();
        info.myasthenia = sql.value(12).toString();
        info.antibody_test = sql.value(13).toString();
        info.blood_test = sql.value(14).toString();
        info.technical_inspection = sql.value(15).toString();
        info.scale_evaluation1 = sql.value(16).toString();
        info.scale_evaluation2 = sql.value(17).toString();
        info.diagnosis1 = sql.value(18).toString();
        info.diagnosis2 = sql.value(19).toString();
        info.treatment_plan = sql.value(20).toString();
        info.MGFA = sql.value(21).toString();
    }
    return info;
}

Info MainWindow::getInfoById(int id)
{
    QSqlQuery sql;
    QString strsql = QString("select * from patient_detail_info where id=%1").arg(id);
    qDebug() << strsql;
    sql.exec(strsql);
    Info info;
    while(sql.next())
    {
        info.id = sql.value(0).toInt();
        info.pid = sql.value(1).toInt();
        info.visit_time = sql.value(2).toString();
        info.first_symptom = sql.value(3).toString();
        info.height = sql.value(4).toString();
        info.weight = sql.value(5).toString();
        info.comorbidity = sql.value(6).toString();
        info.thymic_disease = sql.value(7).toString();
        info.myasthenia = sql.value(8).toString();
        info.antibody_test = sql.value(9).toString();
        info.blood_test = sql.value(10).toString();
        info.technical_inspection = sql.value(11).toString();
        info.scale_evaluation1 = sql.value(12).toString();
        info.scale_evaluation2 = sql.value(13).toString();
        info.diagnosis1 = sql.value(14).toString();
        info.diagnosis2 = sql.value(15).toString();
        info.treatment_plan = sql.value(16).toString();
        info.MGFA = sql.value(17).toString();
    }
    return info;
}

bool MainWindow::isExistFirstInfo(QString id)
{
    QSqlQuery sql;
    QString strsql = QString("select * from patient_detail_first_info where pid=%1").arg(id);
    qDebug() << strsql;
    sql.exec(strsql);
    while(sql.next())
    {
        return true;
    }
    return false;
}

bool MainWindow::delInfoById(QString id)
{
    if(QString::compare(id, "") == 0)
    {
        return false;
    }
    QSqlQuery sql;
    QString strsql = QString("delete from patient_detail_info where id=%1").arg(id);
    qDebug() << strsql;
    return sql.exec(strsql);
}

bool MainWindow::addFirstInfoById(QString id, QString time, QString symptom, QString age, QString passtime, QString height, QString weight, QString smoke, QString pill, QString cill, QString till, QString mill, QString antibody_path, QString blood_path, QString technical_path, QString scale, QString scale_path, QString diagnosis, QString diagnosis_path, QString method, QString MGFA)
{
    QSqlQuery sql;
    QString strsql = QString("insert into patient_detail_first_info(pid, visit_time, first_symptom, first_age, elapsed_time, height, weight, smoking_history, previous_illnesses, comorbidity, thymic_disease, myasthenia, antibody_test, blood_test, technical_inspection, scale_evaluation1, scale_evaluation2, diagnosis1, diagnosis2, treatment_plan, MGFA) values (%1, '%2', '%3', '%4', '%5', '%6', '%7', '%8', '%9', '%10', '%11', '%12', '%13', '%14', '%15', '%16', '%17', '%18', '%19', '%20', '%21')")
            .arg(id).arg(time).arg(symptom).arg(age).arg(passtime).arg(height).arg(weight)
            .arg(smoke).arg(pill).arg(cill).arg(till).arg(mill).arg(antibody_path).arg(blood_path).arg(technical_path)
            .arg(scale).arg(scale_path).arg(diagnosis).arg(diagnosis_path).arg(method).arg(MGFA);
    qDebug() << strsql;
    return sql.exec(strsql);
}

bool MainWindow::addInfoById(QString id, QString time, QString symptom, QString height, QString weight, QString cill, QString till, QString mill, QString antibody_path, QString blood_path, QString technical_path, QString scale, QString scale_path, QString diagnosis, QString diagnosis_path, QString method, QString MGFA)
{
    QSqlQuery sql;
    QString strsql = QString("insert into patient_detail_info(pid, visit_time, symptom, height, weight, comorbidity, thymic_disease, myasthenia, antibody_test, blood_test, technical_inspection, scale_evaluation1, scale_evaluation2, diagnosis1, diagnosis2, treatment_plan, MGFA) values (%1, '%2', '%3', '%4', '%5', '%6', '%7', '%8', '%9', '%10', '%11', '%12', '%13', '%14', '%15', '%16', '%17')")
            .arg(id).arg(time).arg(symptom).arg(height).arg(weight)
            .arg(cill).arg(till).arg(mill).arg(antibody_path).arg(blood_path).arg(technical_path)
            .arg(scale).arg(scale_path).arg(diagnosis).arg(diagnosis_path).arg(method).arg(MGFA);
    qDebug() << strsql;
    return sql.exec(strsql);
}

bool MainWindow::updateFirstInfoById(QString id, QString time, QString symptom, QString age, QString passtime, QString height, QString weight, QString smoke, QString pill, QString cill, QString till, QString mill, QString antibody_path, QString blood_path, QString technical_path, QString scale, QString scale_path, QString diagnosis, QString diagnosis_path, QString method, QString MGFA)
{
    QSqlQuery sql;
    QString strsql = QString("update patient_detail_first_info set visit_time='%1', first_symptom='%2', first_age=%3, elapsed_time='%4', height='%5', weight='%6', smoking_history='%7', previous_illnesses='%8', comorbidity='%9', thymic_disease='%10', myasthenia='%11', antibody_test='%12', blood_test='%13', technical_inspection='%14', scale_evaluation1='%15', scale_evaluation2='%16', diagnosis1='%17', diagnosis2='%18', treatment_plan='%19', MGFA='%20' where pid=%21")
            .arg(time).arg(symptom).arg(age).arg(passtime).arg(height).arg(weight)
            .arg(smoke).arg(pill).arg(cill).arg(till).arg(mill).arg(antibody_path).arg(blood_path).arg(technical_path)
            .arg(scale).arg(scale_path).arg(diagnosis).arg(diagnosis_path).arg(method).arg(MGFA).arg(id);
    qDebug() << strsql;
    return sql.exec(strsql);
}

bool MainWindow::updateInfoById(QString id, QString time, QString symptom, QString height, QString weight, QString cill, QString till, QString mill, QString antibody_path, QString blood_path, QString technical_path, QString scale, QString scale_path, QString diagnosis, QString diagnosis_path, QString method, QString MGFA)
{
    QSqlQuery sql;
    QString strsql = QString("update patient_detail_info set visit_time='%1', symptom='%2', height='%3', weight='%4', comorbidity='%5', thymic_disease='%6', myasthenia='%7', antibody_test='%8', blood_test='%9', technical_inspection='%10', scale_evaluation1='%11', scale_evaluation2='%12', diagnosis1='%13', diagnosis2='%14', treatment_plan='%15', MGFA='%16' where id=%17")
            .arg(time).arg(symptom).arg(height).arg(weight)
            .arg(cill).arg(till).arg(mill).arg(antibody_path).arg(blood_path).arg(technical_path)
            .arg(scale).arg(scale_path).arg(diagnosis).arg(diagnosis_path).arg(method).arg(MGFA).arg(id);
    qDebug() << strsql;
    return sql.exec(strsql);
}

MainWindow::~MainWindow()
{
    delete ui;
}

//点击进入用户界面
void MainWindow::listWidgetClicked(QListWidgetItem *item)
{
    qDebug() << item->statusTip() << " " << ui->listWidget->currentIndex().row() << " " << ui->listWidget->count();
    int id = item->statusTip().toInt();
    User user = getUserById(id);
    us.load(user);
    Info info = getFirstInfoById(id);
    us.load(info);
    QList<Info> list = getAllInfoById(id);
    us.load(list);
    us.showMaximized();
//    updateMainWindow();
}

void MainWindow::on_btn_add_clicked()
{
    add_User.exec();
    ui->le_search->setText("");
    state = false;
    updateMainWindow();
}

void MainWindow::updateMainWindow()
{
    ui->listWidget->clear();

    QFileInfo img("D:/people.jpg");

    QList<QFileInfo> *fileInfo=new QList<QFileInfo>();

    QSqlQuery sql;
    QString strsql = QString("select * from patient_base_info limit 30 offset ") + QString::number(idx * 30);
    qDebug() << strsql;
    sql.exec(strsql);
//    QSqlQueryModel *queryModel = new QSqlQueryModel();
//    queryModel->setQuery(sql);

    if(!sql.exec())
    {
        qDebug() << "Error: Fail to query table. " << sql.lastError();
    }
    else
    {
        while(sql.next())
        {
            int id = sql.value(0).toInt();
            QString name = sql.value(1).toString();
            qDebug()<<QString("id:%1    name:%2").arg(id).arg(name);
            fileInfo->append(img);
            //fileNames.append(img.filePath());
            QListWidgetItem *item = new QListWidgetItem;
            item->setIcon(QIcon(img.filePath()));
            item->setText(name);
            item->setStatusTip(QString::number(id));
            ui->listWidget->addItem(item);
        }
        total = (getUserCnt() + 29) / 30;
        ui->le_page->setText(QString::number(idx + 1) + "/" + QString::number(total));
    }
}

void MainWindow::updateMainWindowBySearch()
{
    ui->listWidget->clear();

    QFileInfo img("D:/people.jpg");

    QList<QFileInfo> *fileInfo=new QList<QFileInfo>();

    QSqlQuery sql;
    QString strsql = QString("select * from patient_base_info where name like '%" + str + "%' limit 30 offset ") + QString::number(idx * 30);
    qDebug() << strsql;
    sql.exec(strsql);
//    QSqlQueryModel *queryModel = new QSqlQueryModel();
//    queryModel->setQuery(sql);

    if(!sql.exec())
    {
        qDebug() << "Error: Fail to query table. " << sql.lastError();
    }
    else
    {
        while(sql.next())
        {
            int id = sql.value(0).toInt();
            QString name = sql.value(1).toString();
            qDebug()<<QString("id:%1    name:%2").arg(id).arg(name);
            fileInfo->append(img);
            //fileNames.append(img.filePath());
            QListWidgetItem *item = new QListWidgetItem;
            item->setIcon(QIcon(img.filePath()));
            item->setText(name);
            item->setStatusTip(QString::number(id));
            ui->listWidget->addItem(item);
        }
        total = (getUserCntByName(str) + 29) / 30;
        ui->le_page->setText(QString::number(idx + 1) + "/" + QString::number(total));
    }
}

void MainWindow::on_btn_search_clicked()
{
    str = ui->le_search->text();
    if(QString::compare(str, "") == 0)
    {
        idx = 0;
        state = false;
        updateMainWindow();
    }
    else
    {
        idx = 0;
        state = true;
        updateMainWindowBySearch();
    }
}

void MainWindow::on_btn_homepage_clicked()
{
    if(idx != 0)
    {
        idx = 0;
    }
    else
    {
        return;
    }
    if(!state)
    {
        updateMainWindow();
    }
    else
    {
        updateMainWindowBySearch();
    }
}

void MainWindow::on_btn_uppage_clicked()
{
    if(idx != 0)
    {
        idx--;
    }
    else
    {
        return;
    }
    if(!state)
    {
        updateMainWindow();
    }
    else
    {
        updateMainWindowBySearch();
    }
}

void MainWindow::on_btn_nextpage_clicked()
{
    if(idx != total - 1)
    {
        idx++;
    }
    else
    {
        return;
    }
    if(!state)
    {
        updateMainWindow();
    }
    else
    {
        updateMainWindowBySearch();
    }
}

void MainWindow::on_btn_lastpage_clicked()
{
    if(idx != total - 1)
    {
        idx = total - 1;
    }
    else
    {
        return;
    }
    if(!state)
    {
        updateMainWindow();
    }
    else
    {
        updateMainWindowBySearch();
    }
}
